package com.bclz.config.httpclient;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ch.qos.logback.classic.Logger;

@Service
public class HttpClientService {
	
	private Logger log=(Logger)LoggerFactory.getLogger(getClass());
	
	@Autowired
	private HttpClient client;
	
	public  String doPost(String url ,Map<String,String> params) {
		
		BufferedReader in = null;  
        try {  
            // 实例化HTTP方法  
            HttpPost request = new HttpPost();  
            request.setURI(new URI(url));
            
            //设置参数
            List<NameValuePair> nvps = new ArrayList<NameValuePair>(); 
            for (Iterator<String> iter = params.keySet().iterator(); iter.hasNext();) {
    			String name = (String) iter.next();
    			String value = String.valueOf(params.get(name));
    			nvps.add(new BasicNameValuePair(name, value));
    			
    		}
            request.setEntity(new UrlEncodedFormEntity(nvps,"UTF-8"));
            
            HttpResponse response = client.execute(request);  
            int code = response.getStatusLine().getStatusCode();
            if(code == 200){	//请求成功
            	in = new BufferedReader(new InputStreamReader(response.getEntity()  
                        .getContent(),"utf-8"));
                StringBuffer sb = new StringBuffer("");  
                String line = "";  
                String NL = System.getProperty("line.separator");  
                while ((line = in.readLine()) != null) {  
                    sb.append(line + NL);  
                }
                
                return sb.toString();
            }
            else{	//
            	log.info("HttpClient请求URL:{}  状态码:{}",url, code);
            	return null;
            }
        }catch(Exception e){
        	log.error("HttpClient请求出错:",e);
        	return null;
        }finally{
            try {
            	if(in!=null){
                    in.close();
                }
        	} catch (Exception e) {
        		log.error("HttpClient关闭流出错:",e);
        	}

        }


	}
	
}
